package cn.bonoon.kernel.web.handlers;

import cn.bonoon.handler.impl.StandardAutoManager;
import cn.bonoon.kernel.descriptors.ObjectDescriptor;
import cn.bonoon.kernel.support.OperandSupport;
import cn.bonoon.kernel.support.entities.Persistable;
import cn.bonoon.kernel.support.services.GenericService;
import cn.bonoon.kernel.support.services.IService;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.BaseButtonResolver;
import cn.bonoon.kernel.web.controllers.GridButtonResolver;
import cn.bonoon.kernel.web.controllers.GridToolbarResolver;
import cn.bonoon.kernel.web.html.form.FormBuilder;
import cn.bonoon.kernel.web.html.form.StandardInsertBuilder;

/**
 * 添加对话框
 * @author jackson
 *
 * @param <E>
 * @param <R>
 */
public class DialogInsertHandler<E extends Persistable> extends AbstractDialogFormableHandler<E>{
	
	/**
	 * <pre>
	 * 注意，这个构造函数没有自动添加“添加操作”的提交按钮
	 * </pre>
	 * @param register
	 * @param service
	 * @param editClass
	 * @throws Exception 
	 */
	public DialogInsertHandler(HandlerRegister register, IService<E> service, Class<?> editClass) throws Exception {
		super(register, service, editClass);
	}
	
	public DialogInsertHandler(HandlerRegister register, GenericService<E> service, Class<?> editClass) throws Exception {
		this(register, new OperateInsertHandler<E>(service, register.getManager(), editClass));
	}
	
	public DialogInsertHandler(HandlerRegister register, AbstractOperateFormHandler<E> insertHandler) throws Exception {
		super(register, insertHandler.service, insertHandler.editClass);
		defaultButton = insertHandler;
	}

	@Override
	protected FormBuilder builder(ObjectDescriptor objectDescriptor, StandardAutoManager manager) {
		return new StandardInsertBuilder(objectDescriptor, manager);
	}

	/**
	 * 在添加界面用于替换父类中的{@link AbstractDialogFormableHandler#register(GridButtonResolver)}
	 * @param resolver
	 * @return
	 * @throws Exception
	 */
	@Override
	public BaseButtonResolver register(BaseButtonResolver resolver) throws Exception {
		if(StringHelper.isEmpty(title)){
//			set("添加信息", true);
			title = "添加信息";
		}
		closeButton = true;
		resolver.setName("添加");
		resolver.setKey(OperandSupport.DIALOG_INSERT);
		resolver.setIconCls("icon-add2");
		return super.register(resolver);
	}
	
	/**
	 * <pre>
	 * 向toolbar上追加"添加"按钮
	 * </pre>
	 * @param register
	 * @param genericService
	 * @param editClass
	 * @return
	 * @throws Exception 
	 */
	public static <E extends Persistable> GridToolbarResolver toolbar(HandlerRegister register, GenericService<E> genericService, Class<?> editClass) throws Exception{
		DialogInsertHandler<E> dih = new DialogInsertHandler<E>(register, genericService, editClass);
		GridToolbarResolver gtr = register.toolbar();
		dih.register(gtr);
		return gtr;
	}
}